//
//  CAGoodsListViewController.m
//  LNH
//
//  Created by twentylx on 2018/1/16.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAGoodsListViewController.h"
#import "CAGoodsListCollectionViewCell.h"
#import "CAGoodsListHeaderView.h"
#import <MJRefresh/MJRefresh.h>
#import "CAGoodsListApi.h"
#import "UIImageView+WebCache.h"
#import "LNHGoodsDetailViewController.h"
#import "CAUpgradeViewController.h"

@interface CAGoodsListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate> {
    NSInteger _page;
}

@property (nonatomic, strong) CAGoodsListHeaderView *headerView;

@property (nonatomic, strong) UICollectionView *goodsListCollectionView;
@property (nonatomic, strong) NSMutableArray *goodsArray;

@end

@implementation CAGoodsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

#pragma mark - 方法绑定
/// 初始化数据
- (void)lm_initialDefaultsForController {
}

/// 绑定 vm
- (void)lm_bindViewModelForController{
    
}

/// 创建视图
- (void)lm_createViewForController{
//    [self.view addSubview:self.headerView];
    [self.view addSubview:self.goodsListCollectionView];
    
     [self.view setNeedsUpdateConstraints];
}

/// 配置导航栏
- (void)lm_configNavigationForController{
    self.navigationItem.title = self.vcTitle;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = RGBCOLOR(113, 113, 113);
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : RGBCOLOR(35, 24, 21), NSFontAttributeName : [UIFont systemFontOfSize:16]};
    
    
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}

#pragma mark layout
- (void) updateViewConstraints {
    [_goodsListCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [super updateViewConstraints];
}

#pragma mark get & set
- (CAGoodsListHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[CAGoodsListHeaderView alloc] initWithFrame:(CGRect){0, 0, SCREEN_WIDTH, 300}];
        
        UITapGestureRecognizer *gesture = [UITapGestureRecognizer new];
        [self.headerView.vipImageView addGestureRecognizer:gesture];
        [[gesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            CAUpgradeViewController *upgradeVC = [CAUpgradeViewController new];
            upgradeVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:upgradeVC animated:YES];
        }];
    }
    return _headerView;
}

- (UICollectionView *) goodsListCollectionView {
    if (!_goodsListCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setMinimumLineSpacing:10];
        [layout setMinimumInteritemSpacing:0];
        [layout setSectionInset:(UIEdgeInsets){ 0, 20, 20, 20 }];
        [layout setItemSize:CGSizeMake((SCREEN_WIDTH-60)/2, 280)];
        if (self.isYPH > 0) {
            [layout setHeaderReferenceSize:(CGSize){SCREEN_WIDTH, 300}];
        } else {
            [layout setHeaderReferenceSize:(CGSize){SCREEN_WIDTH, 40}];
        }
        
        _goodsListCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _goodsListCollectionView.backgroundColor = [UIColor whiteColor];
        
        [_goodsListCollectionView registerClass:[CAGoodsListCollectionViewCell class] forCellWithReuseIdentifier:@"goodsCell"];
        [_goodsListCollectionView registerClass:[CAGoodsListHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
        _goodsListCollectionView.delegate = self;
        _goodsListCollectionView.dataSource = self;
        
        WS(weakSelf);
        _goodsListCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshData];
        }];
        
        _goodsListCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadMoreData];
        }];
        
        [_goodsListCollectionView.mj_header beginRefreshing];
        
    }
    return _goodsListCollectionView;
}

#pragma mark private method
- (void) refreshData {
    _page = 1;
    CAGoodsListApi *goodsListApi = [[CAGoodsListApi alloc] initWithCategory:self.category IsFavourable:self.isYPH IsVip:self.isVip IsSecond:self.isSecond GoodsName:self.goodsName Page:[NSString stringWithFormat:@"%ld", _page]];
    
    [goodsListApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [_goodsListCollectionView.mj_header endRefreshing];
        CAGoodsListApi *api = (CAGoodsListApi *) request;
        NSLog(@"%@", api.responseObject);
        if (api.done) {
            self.goodsArray = [NSMutableArray arrayWithArray:request.responseJSONObject[@"result"][@"data"]];
            [self.goodsListCollectionView reloadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [_goodsListCollectionView.mj_header endRefreshing];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) loadMoreData {
    _page++;
    CAGoodsListApi *goodsListApi = [[CAGoodsListApi alloc] initWithCategory:self.category IsFavourable:self.isYPH IsVip:self.isVip IsSecond:self.isSecond GoodsName:self.goodsName Page:[NSString stringWithFormat:@"%ld", _page]];
    [goodsListApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [_goodsListCollectionView.mj_footer endRefreshing];
        CAGoodsListApi *api = (CAGoodsListApi *) request;
        if (api.done) {
            [self.goodsArray addObjectsFromArray:request.responseJSONObject[@"result"][@"data"]];
            [self.goodsListCollectionView reloadData];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [_goodsListCollectionView.mj_footer endRefreshing];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark UIConllectionView DataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.goodsArray.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CAGoodsListCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"goodsCell" forIndexPath:indexPath];
    NSDictionary *dict = self.goodsArray[indexPath.row];
    
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, dict[@"goods_img"]];
    [cell.goodsImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    cell.goodsTitleLabel.text = dict[@"name"];
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%@", dict[@"price"]];
    if ([_isYPH isEqualToString:@"0"]) {
        cell.vipLabel.hidden = YES;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = self.goodsArray[indexPath.row];

    NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(LNHGoodsDetailViewController.class)] extraParameters:@{@"goodsId":dict[@"id"]}];
    [[RACScheduler mainThreadScheduler] schedule:^{

        [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:@{} completionHandler:nil];

    }];
   
}

#pragma mark - 头部或者尾部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        CAGoodsListHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        if (!self.isYPH) {
            headerView.vipImageView.hidden = YES;
            headerView.titleLabel.hidden = YES;
            headerView.lineView.hidden = YES;
        }
        
        return headerView;
        
    } else {
        return nil;
    }
}

@end
